package com.ruoyi.web.controller.common;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.OssUtils;
import io.swagger.annotations.Api;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.UUID;

@RestController
@Api(tags = "OSS对象存储Controller")
@RequestMapping("/oss")
public class OssController {
    @Autowired
    OssUtils ossUtils;
    @Value("${ruoyi.profile}")
    private String uploadPath;
    @Value("${ruoyi.domain}")
    private String domain;

    @SneakyThrows
    @PostMapping("upload")
    public AjaxResult uploadFile(MultipartFile file) {
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();

        // 生成新的文件名(避免重名)
        String fileName = UUID.randomUUID().toString() +
                originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileUrl = domain + "/files/" + fileName;
        System.out.println("fileUrl: "+fileUrl);
        // 创建目标目录
        File dest = new File(uploadPath);
        if (!dest.exists()) {
            dest.mkdirs();
        }
        String filePath =  uploadPath + "/" + fileName;
        System.out.println("fileName和path:"+filePath);
        // 保存文件到本地
        File saveFile = new File(filePath);
        file.transferTo(saveFile);


        AjaxResult ajax = AjaxResult.success();
        ajax.put("fileName", originalFilename);
        ajax.put("url", fileUrl);
        return ajax;
    }

    @PostMapping("uploadArrayFile")
    public List<String> uploadArrayFile(MultipartFile[] files) {
        //返回上传oss的url
        return ossUtils.uploadArrayFile(files);
    }

    @PostMapping("deleteFile")
    public boolean deleteFile(@RequestBody String fileUrl) {
        //返回是否删除成功
        return ossUtils.deleteFile(fileUrl);
    }
}
